package com.csbaic.web.interceptor;

import com.csbaic.web.annotation.ResponseResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class ResponseResultInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod methodHandle = (HandlerMethod) handler;
        Method method = methodHandle.getMethod();
        Class<?> clz = methodHandle.getBeanType();

        if(clz.isAnnotationPresent(ResponseResult.class)){
            request.setAttribute(ResponseResult.class.getName(), clz.getAnnotation(ResponseResult.class));
        }else if(method.isAnnotationPresent(ResponseResult.class)){
            request.setAttribute(ResponseResult.class.getName(), method.getAnnotation(ResponseResult.class));
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}


